/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: jse2204 - VolatileTest
 * <p>Powered by webrx On 2022-09-30 14:28:39
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class VolatileTest {
    int count = 0;

    synchronized void m() {
        for (int i = 0; i < 100; i++) count++;
    }

    AtomicInteger sum = new AtomicInteger(0);

    void mm() {
        for (int i = 0; i < 100; i++) sum.incrementAndGet();
    }

    public static void main(String[] args) throws Exception {

        var t = new VolatileTest();
        long ss = System.currentTimeMillis();
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            list.add(new Thread(t::m));
        }

        list.forEach(Thread::start);
        list.forEach(o -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(System.currentTimeMillis() - ss);
        System.out.println(t.count);

        System.out.println("------------------------------");

        list.clear();
        ss = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            list.add(new Thread(t::mm));
        }

        list.forEach(Thread::start);
        list.forEach(o -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(System.currentTimeMillis() - ss);
        System.out.println(t.sum.get());
    }
}
